package com.cskaoyan.market.controller;


import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.service.AdminAuthService;
import com.cskaoyan.market.service.impl.AdminAuthServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/auth/*")
public class AdminAuthController extends HttpServlet {

    private AdminAuthService adminAuthService = new AdminAuthServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/auth/", "");
        if("info".equals(op)){
            info(req, resp);
        }
    }

    private void info(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从session域中获取数据
        HttpSession session = req.getSession();
        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");
        Map<String, Object> data = new HashMap<>();
        //roles、perms是权限相关的内容，项目二介绍，项目一固定返回这部分数据即可
        data.put("roles", new String[]{"超级管理员"});
        data.put("name", admin.getUsername());
        data.put("perms", new String[]{"*"});
        data.put("avatar", admin.getAvatar());
        Object ok = ResponseUtil.ok(data);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ok));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/auth/", "");
        if("login".equals(op)){
            login(req, resp);
        }
    }

    /**
     * login接口的业务流程：
     * 1.接收用户提交过来的请求参数信息：参数的格式是什么？位于请求体中，是json字符串
     * 可以使用request.getParameter来接收吗？不可以，因为不是key=value&key=value
     * 2.校验
     * 3.系统中进行比对处理
     * 4.返回回执信息----不可以像之前一样response.getWriter().println(中文)
     * 前后端对接的情况下，后端的返回结果会被前端代码所解析 获取json字符串里面的数据
     * 需要做的事情便是返回和101上面一致的返回值
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        req.getParameter("username")
//        new BufferedReader(new InputStreamReader())
        //使用下面两种方式均可，但是下面第二种更方便一些
//        req.getInputStream();
        // {"username":"admin123", "password":"admin123"}
        String requestBody = req.getReader().readLine();
        System.out.println(requestBody);
        //将json字符串转换成java类型，需要创建一个对象，但是我不想创建
        //如果一个json字符串中只有一两个属性值，建议使用下面的方式，因为如果直接用
        //obejctMapper.readValue还需要去创建一个对象，繁琐
        String username = JacksonUtil.parseString(requestBody, "username");
        String password = JacksonUtil.parseString(requestBody, "password");
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //TODO
            //这里面的状态码只要不是0，系统都认为是错误状态码，每个商城都会制定一系列的状态码
            //根据返回的不同状态码，便可以知道因为什么问题导致的失败，自己可以自行去确定
            Object o = ResponseUtil.fail(605, "用户名或者密码不能为空");
            String s = JacksonUtil.writeValueAsString(o);
            resp.getWriter().println(s);
            return;
        }
        //service的返回值应该写什么？
        MarketAdmin marketAdmin = adminAuthService.login(username, password);
        if(marketAdmin == null){
            Object o = ResponseUtil.fail(605, "用户帐号或密码不正确");
            String s = JacksonUtil.writeValueAsString(o);
            resp.getWriter().println(s);
            return;
            //登录失败  {"errno":605,"errmsg":"用户帐号或密码不正确"}
        }
        //登录成功
//        {
//            "errno": 0,
//                "data": {
//            "adminInfo": {
//                "nickName": "admin123",
//                "avatar": "http://101.43.69.31:8083/wx/storage/fetch/q5al5ys6vh38yrcsv11z.gif"
//            },
//            "token": "450bdcb7-8256-4cca-bd01-1210d21fe4ec"
//        },
//            "errmsg": "成功"
//        }
        HttpSession session = req.getSession();
        session.setAttribute("admin", marketAdmin);
        String id = session.getId();
        Map<String, Object> data = new HashMap<>();
        Map<String, String> info = new HashMap<>();
        info.put("nickName", marketAdmin.getUsername());
        info.put("avatar", marketAdmin.getAvatar());
        data.put("adminInfo", info);
        data.put("token", id);
        Object ok = ResponseUtil.ok(data);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ok));
    }
}

